<template>
    <div>
        <el-upload ref="uploadRef" action="" list-type="text" :accept="props.upInfo.acceptFile"
            :multiple="props.upInfo.multiple"
            :before-upload="beforeUpdata"
            :http-request="onHttpRequest"
            :show-file-list="false"
            :file-list="props.upInfo.upFile" >
            <template #default>
                <slot></slot>
            </template>
        </el-upload>
        <el-dialog custom-class="upLoadImg-dialog-box" v-model="appDialog.visible"
            :close-on-click-modal="!appDialog.closeModal" :width="appDialog.width" destroy-on-close append-to-body>
            <div class="upLoadImg-content">{{ content }}</div>
            <template #footer>
                <el-button @click="changeImg">{{ appDialog.cancelText }} </el-button>
                <el-button type="primary" @click="confirmImgZip">{{ appDialog.submitText }} </el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElForm, ElMessage, ElLoading } from 'element-plus'
import type { UploadFile } from 'element-plus/es/components/upload/src/upload'

import { uploadFile2 } from '@renderer/ajax/api/common'
import { getImage_wh, IsNotEmpty, playTime } from '../../utils'
import ImageCompressor from 'js-image-compressor'
const uploadRef = ref<any>(null)
const emit = defineEmits(['submit'])
const formRef = ref<InstanceType<typeof ElForm>>()
const props = defineProps(['upInfo', 'remainNum'])

const zipImgInfo = ref<any>('')
const content = ref('您上传的图片大小已经超过了最大限制！如果继续，图片将会自动压缩处理。但请注意，压缩后的图片会影响图片的清晰度，请知晓！')
const appDialog = reactive<any>({
    visible: false,
    title: '提示！',
    width: '400px',
    cancelText: '换一张',
    submitText: '继续'
})

const beforeUpdata = async (file: any) => {
    const { acceptFile, limitSize } = props.upInfo
    const is2M = file.size / 1024 / 1024 <= limitSize
    let tips = '图片'
    switch (props.upInfo.type) {
        case 1:
            tips = '图片'
            const { W, H } = await getImage_wh(file)
            let WH = W * H
            let ext = file.name.substring(file.name.lastIndexOf('.'))
            if (acceptFile.indexOf(ext) == -1) {
                ElMessage.warning(`该图片是${ext}格式,请上传${acceptFile}格式图片`)
                return false
            }
            if (WH > 1555200) {
                // ElMessage.warning(`该图片总像素是${WH},超过最大图片总像素1555200`)
                appDialog.visible = true
                zipImgInfo.value = file
                return false
            }
            if (H > 10800) {
                appDialog.visible = true
                zipImgInfo.value = file
                return false
            }
            break
        case 4:
            tips = '语音'
            break
        case 2:
            tips = '视频'
            let extMp4 = file.name.substring(file.name.lastIndexOf('.'))
            if ('.mp4,.MP4'.indexOf(extMp4) == -1) {
                ElMessage.warning(`只能上传Mp4格式`)
                return false
            }
            if (!is2M) {
                ElMessage.warning(`上传的${tips}最大支持${limitSize}M`)
                return false
            }
            const res: any = await playTime(file)
            if (res > 30) {
                ElMessage.warning(`上传的视频不能超过30s`)
                return false
            }
            break
        case 5:
            tips = '文件'
            break
        default:
            tips = ''
    }
    if (!is2M) {
        if (props.upInfo.type == 1) {
            appDialog.visible = true
            zipImgInfo.value = file
        } else {
            ElMessage.warning(`上传的${tips}最大支持${limitSize}M`)
        }
        return false
    }
    return is2M
}
// 上传文件
const uploadImg = async (file: any) => {
    let flag = await beforeUpdata(file)
    if (!flag) return false
    return await uploadFile2(file)
}
// 上传改变
let loading = null
const onHttpRequest = async ({ file }: UploadFile) => {
    try {
        loading = ElLoading.service({
            lock: true,
            text: '文件上传中....',
        })
        const data: any = await uploadImg(file)
        emit('submit', { ...data, type: props.upInfo.type })
        uploadRef.value.clearFiles()
    } catch (e) {
        ElMessage.error(e?.message || e)
        uploadRef.value.clearFiles()
    } finally {
        loading?.close()
    }
}

const changeImg = () => {
    // uploadRef.value.$refs["uploadRef"].handleClick()
    appDialog.visible = false

    const e = document.createEvent("MouseEvents");
    e.initEvent("click", true, true);
    document.getElementById("localUpload")?.dispatchEvent(e);
}

const confirmImgZip = () => {
    compressImg(zipImgInfo.value)
}

const compressImg = (file: any) => {
    let options = {
        file: file,
        maxWidth: 1440,
        maxHeight: 1080,
        quality: 0.8,
        success: async (res: any) => {
            console.log(res, '1')
            console.log('压缩之后图片尺寸大小: ', res.size);
            let files = new File([res], res.name, { type: res.type, lastModified: res.lastModified });
            files.width = res.width
            files.height = res.height
            files.uid = file.uid
            console.log(files, 'files')
            if (res.size / 1024 / 1024 <= 10) {
                const data: any = await uploadFile2(files)
                emit('submit', { ...data.data, type: props.upInfo.type })
                uploadRef.value.clearFiles()
                appDialog.visible = false
            } else {
                compressImg(files)
            }
        }
    }
    new ImageCompressor(options);
}
</script>
<style lang="scss" scoped>
.pre_img_box {
    overflow: hidden;

    .pre_image {
        display: block;
        margin: auto;
        max-height: 400px;
    }
}

.upLoadImg-dialog-box {
    .upLoadImg-content {
        padding: 50px 30px 24px;
        line-height: 26px;
        text-align: left;
    }

    .img-dialog-footer {
        display: flex;
        justify-content: flex-end;
        border-top: 1px solid #e8e8e8;

        .footer-right {
            margin-left: 10px;
        }
    }
}
</style>
<style>
.hide .el-upload--picture-card {
    display: none;
}

.upload_icon {
    width: 140px;
    height: 90px;
}
</style>
